/**
 *
 * @authors 杨兴洲（of2502）
 * @date    2017/3/14 10:55
 * @version 1.0
 */
import {Router} from "express";
import UserService from "../../service/user-service";
import WeixinMessageService from "../../service/weixin-message-service";
import ReplyService from "../../service/reply-service";
import logger from "../../util/logger";

const router = Router();

const checkFollowRule = (req, res, next) => {
    const {type, content} = req.body;

    // type
    if (!["text", "image", "voice", "video", "mpnews", "news"].includes(type)) {
        const error = new Error();
        error["errcode"] = 10002;
        error["errmsg"] = "type参数类型不正确";
        return next(error);
    }

    // content
    if (!content) { // null || ""
        const error = new Error();
        error["errcode"] = 10002;
        error["errmsg"] = "content不能为空";
        return next(error);
    }

    next();
};

/**
 * 获取自动回复规则列表
 */
router.get('/rules', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const result = await ReplyService.getRules(appID);
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取微信自动回复规则
 */
router.get('/rules/weixin', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const access_token = await UserService.getAccessToken(userID);
            const result = await WeixinMessageService.getAutoReplyRules({access_token});
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 同步微信自动回复规则
 * @废弃
 */
router.post('/rules/sync', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const access_token = await UserService.getAccessToken(userID);
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            // 获取规则
            const rules = await WeixinMessageService.getAutoReplyRules({access_token});
            // 同步规则
            const result = await ReplyService.setRules({appID, rules});
            // xxx
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 切换微信自动回复规则
 * @暂时无用...
 */
router.post('/rules/toggle', (req, res, next) => {
    (async () => {
        try {
            const {isOpen} = req.body;
            const {userID} = res.locals;
            // 验证参数
            if (!["0", "1", 0, 1].includes(isOpen)) {
                return res.status(200).json({
                    errcode: "10002",
                    errmsg: "参数类型不正确"
                });
            }
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const rules = {
                "is_add_friend_reply_open": +isOpen,
                "is_autoreply_open": +isOpen
            };
            const result = await ReplyService.setRules({appID, rules});
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取关注时回复规则
 */
router.get('/rule/follow', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const {add_friend_autoreply_info} = await ReplyService.getRules(appID);
            const result = add_friend_autoreply_info || {};
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 更新关注时回复规则
 */
router.post('/rule/follow/update', [checkFollowRule], (req, res, next) => {
    (async () => {
        try {
            const {type, content, title, url} = req.body;
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);

            let rule: any = {
                type, content
            };
            if (type === "image") rule.url = url;
            if (type === "news" || type === "mpnews") rule.title = title;
            const result = await ReplyService.updateAddFriendRule({appID, rule});
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 更新关注时回复规则
 */
router.post('/rule/follow/delete', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const result = await ReplyService.deleteAddFriendRule(appID);
            logger.debug(result);
            res.status(200).json({
                errcode: 0,
                errmsg: "默认消息规则删除成功"
            });
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取消息默认回复规则
 */
router.get('/rule/default', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const {message_default_autoreply_info} = await ReplyService.getRules(appID);
            const result = message_default_autoreply_info || {};
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 更新消息默认回复
 */
router.post('/rule/default/update', [checkFollowRule], (req, res, next) => {
    (async () => {
        try {
            const {type, content} = req.body;
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const result = await ReplyService.updateMessageDefaultRule({appID, rule: {type, content}});
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 删除消息默认回复
 */
router.post('/rule/default/delete', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const result = await ReplyService.deleteMessageDefaultRule(appID);
            logger.debug(result);
            res.status(200).json({
                errcode: 0,
                errmsg: "默认消息规则删除成功"
            });
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取关键词回复规则列表(分页)
 */
router.get('/rule/keyword/list', (req, res, next) => {
    (async () => {
        try {
            const {userID} = res.locals;
            const {page, pageSize} = req.query;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const result = await ReplyService.getKeywordRuleListByPage({appID, page: +page, pageSize: +pageSize});
            logger.debug("关键词回复规则列表", result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 创建某条关键词回复规则
 * 暂时不去重，微信官方也没有做
 */
router.post('/rule/keyword/create', (req, res, next) => {
    (async () => {
        try {
            const {rule} = req.body;
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            // let {type, content, url, title} = rule;
            // let data: any = {type, content};
            // if (type === "image") data.url = url;
            // if (type === "news" || type === "mpnews") data.title = title;
            const result = await ReplyService.createKeywordRule({appID, rule});
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 删除某条关键词回复规则
 */
router.post('/rule/keyword/delete', (req, res, next) => {
    (async () => {
        try {
            const {ruleID} = req.body;
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const result = await ReplyService.deleteKeywordRule({appID, ruleID});
            logger.debug(result);
            res.status(200).json({
                errcode: 0,
                errmsg: `规则id:${ruleID}删除成功`
            });
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 更新某条关键词回复规则
 */
router.post('/rule/keyword/update', (req, res, next) => {
    (async () => {
        try {
            const {ruleID, rule} = req.body;
            // let {type, content, url, title} = rule;
            // let data: any = {type, content};
            // if (type === "image") data.url = url;
            // if (type === "news" || type === "mpnews") data.title = title;
            const result = await ReplyService.updateKeywordRule({ruleID, rule});
            logger.debug(result);
            res.status(200).json({
                errcode: 0,
                errmsg: `规则id:${ruleID}更新成功`
            });
        } catch (error) {
            next(error);
        }
    })();
});

/**
 * 获取某条关键词回复规则
 */
router.get('/rule/keyword/detail', (req, res, next) => {
    (async () => {
        try {
            const {ruleID} = req.query;
            const {userID} = res.locals;
            const {authorizer_appid: appID} = await UserService.getInfo(userID);
            const result = await ReplyService.getKeywordRule({appID, ruleID});
            logger.debug(result);
            res.status(200).json(result);
        } catch (error) {
            next(error);
        }
    })();
});

export default router;
